
var chatPlugin;


//手写输入系统
chatPlugin = function(){


	//重写聊天api调用函数
	function chat_api_funcion(chat_api_url,text,historyArr,callBack){
		$.ajax({
				method: "POST",
				url: chat_api_url,
				contentType: 'application/json',
				data:JSON.stringify({"prompt": text, "history": historyArr}),
				success: function( data ) {
					console.log("chat_api_funcion")
					console.log(data)
					if(data && data.response){
						if(callBack){
							callBack(data.response);
						}
					}
			   }
		});
	}

	//重写语音api调用函数
	function sound_api_funcion(sound_api_url,text,callBack){
		_ajaxGetSoundPathByText(sound_api_url,text,callBack)
	}


	var textToMusicPathObj = {};
	
	//初始化选择的语音模型
	function ajaxInitSoundConfig(sound_api_url,callBack){
			$.ajax({
				method: "POST",
				url: sound_api_url+"/run/predict",
				contentType: 'application/json',
				data:JSON.stringify({"fn_index":1,"data":["pretrained"],"event_data":null,"session_hash":"608m1lu3cbn"}),
				success: function( data ) {
					console.log(data)
					if(callBack){
						callBack(data)
					}
			   }
			});
	}
	
	function _ajaxGetSoundPathByText(sound_api_url,text,callBack,retry){
		if(textToMusicPathObj[text]){
			callBack(sound_api_url+"/file="+textToMusicPathObj[text]);
			return;
		}
			$.ajax({
				method: "POST",
				url: sound_api_url+"/run/predict",
				contentType: 'application/json',
				data:JSON.stringify({"fn_index":3,"data":["中英，英文（可选项）需要使用[EN][EN]包裹",text,"标贝女声",0.666,0.668,1.2],"event_data":null,"session_hash":"608m1lu3cbn"}),
				success: function( data ) {
					//console.log(data)
					if(data && data.data && data.data[0] && data.data[0].name){
						var music_path = data.data[0].name;
						textToMusicPathObj[text] = music_path;
						//console.log(music_path)
						callBack(sound_api_url+"/file="+music_path);
					}
					
			   },
			   error:function(data){
				   //console.log("error")
				   //console.log(data)
				   ajaxInitSoundConfig(sound_api_url,function(){
					   //如果没有重试过，则尝试重试
					   if(!retry){
						   _ajaxGetSoundPathByText(text,callBack,1);
					   }
				   });
			   }
			});
	}


		return{
		chat_api_funcion:chat_api_funcion,
		sound_api_funcion:sound_api_funcion,
	}
}();
	
	
	

